//
//  SearchListController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/13.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "SearchListController.h"

#import "ZZShareView.h"


#import "ZZHomeListCell.h"
#define cellIdentifier @"ZZHomeListCell"

#import "ZZTalkListCell.h"
#define cellIdentifierTZ @"ZZTalkListCell"


#import "ZZUserListCell.h"
#define cellIdentifierUser  @"ZZUserListCell"

#import "UserInfoController.h"
#import "TalkDetailController.h"
#import "ZZContentDetailController.h"

@interface SearchListController ()<ZZTopicCellDelegate,UITableViewDelegate,UITableViewDataSource>{
    int _page;
}

@property(nonatomic,strong) NSMutableArray *searchArray;

@property(nonatomic,strong)  UITableView *listTable;

@property (nonatomic, assign) BOOL status;

@end

@implementation SearchListController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationBar];
    
    _searchArray = [[NSMutableArray alloc] init];
    
    _page = 1;
    [self createTableView];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    [self.navigationController setNavigationBarHidden:YES];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}


-(void)actionBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)setSearchType:(int)searchType{
    _searchType = searchType;
    [self loadBegin];
}

-(void)setSearchText:(NSString *)searchText{
    _searchText = searchText;
    [self loadBegin];
}

-(void)loadBegin{
    _page = 1;
    [self loadMoreData];
}

/**
 加载更多
 */
-(void)loadMoreData{
    
    NSString *typeStr = @"sucai";
    if(_searchType == 2){
        typeStr = @"thread";
    }
    if(_searchType == 3){
        typeStr = @"user";
    }
    
    if(convertToString(_searchText).length == 0){
        [self.listTable reloadData];
        return;
    }
    [NetworkUtil POST:API_SearchList parameters:@{@"keyword":convertToString(_searchText),@"type":typeStr,@"nav_type":@"",@"page":convertIntToString(_page)} success:^(id responseObject, NSDictionary *dict) {
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        
        NSArray *arr = nil;
        if(self.searchType == 1){
            arr = dict[@"data"][@"list"][@"avatar"];
        }else{
            arr  = dict[@"data"][@"list"];
        }
        if(arr == nil){
            return;
        }
        
        if(self->_page == 1){
            [self.searchArray removeAllObjects];
        }
        
        if(self.searchType == 1){
            for (NSDictionary *item in arr) {
                [self.searchArray addObject:[[ZZHomeTopicEntity alloc] initWithDictionary:item]];
            }
        }
        if(self.searchType == 2){
            for (NSDictionary *item in arr) {
                [self.searchArray addObject:[[ForumEntity alloc] initWithDictionary:item]];
            }
        }
        if(self.searchType == 3){
            for (NSDictionary *item in arr) {
                [self.searchArray addObject:[[User alloc] initWithDictionary:item]];
            }
        }
        
        self.status = (self.searchArray.count==0);
        [self.listTable reloadData];
        
        if(convertToString(dict[@"data"][@"page"]).length>0){
            if([dict[@"data"][@"page"] intValue] < [dict[@"data"][@"pages"] intValue]){
                self->_page = [dict[@"data"][@"page"] intValue] + 1;
            }
        }
        
//#warning - 注：由于接口没有返回pages字段，不知道总页数是多少，所以总会++
//        self->_page ++;
    } failure:^(NSError *error, NSString *message) {
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        self.status = (self.searchArray.count==0);
        [self.listTable reloadData];
    }];
}

-(void)createTableView{
    _status = NO;

    _listTable=[self.view createTableView:self cell:cellIdentifier];
    [_listTable setFrame:self.view.bounds];
    _listTable.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [_listTable registerNib:[UINib nibWithNibName:cellIdentifierUser bundle:nil] forCellReuseIdentifier:cellIdentifierUser];
    [_listTable registerNib:[UINib nibWithNibName:cellIdentifierTZ bundle:nil] forCellReuseIdentifier:cellIdentifierTZ];
    
    [_listTable setBackgroundColor:UIColor.whiteColor];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    
    [self setTableSeparatorInset];
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    [footer setTitle:Uncontent_floor forState:MJRefreshStateNoMoreData];
    _listTable.footer = footer;
    
}



-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    [ZZCoreTools sucaiListenerImpl:senderObj type:type page:self refresh:_listTable];
}


#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    if(section == 0){
        
    }
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.status) {
        return 1;
    }
    return _searchArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.status) {
        DefaultCell *cell = [[DefaultCell alloc] init];
        [cell.labText setText:Uncontent_search];
        return cell;
    }
    
    if(_searchType == 1){
        
        ZZHomeListCell *cell = (ZZHomeListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[ZZHomeListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        cell.delegate = self;
        [cell dataToView:[_searchArray objectAtIndex:indexPath.row]];
        return cell;
    }
    if(_searchType == 2){
        
        ZZTalkListCell *cell = (ZZTalkListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifierTZ];
        if (cell == nil) {
            cell = [[ZZTalkListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierTZ];
        }
        cell.delegate = self;
        [cell dataToView:[_searchArray objectAtIndex:indexPath.row]];
        return cell;
    }
    if(_searchType == 3){
        ZZUserListCell *cell = (ZZUserListCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifierUser];
        if (cell == nil) {
            cell = [[ZZUserListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierUser];
        }
        cell.btnAttent.hidden = YES;
        cell.labName.attributedText = [NSAttributedString new];
        [cell dataToView:[_searchArray objectAtIndex:indexPath.row]];
        return cell;
        
    }
    
    return nil;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.status) {
        return ScreenHeight - StatusBarHeight - NavBarHeight;
    }
    
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(_searchType == 1){
        
        ZZHomeTopicEntity *model=[_searchArray objectAtIndex:indexPath.row];
        ZZContentDetailController *vc = [[ZZContentDetailController alloc] init];
        vc.entity = model;
        [self openPushVC:vc];
    }else if(_searchType == 2){
        ForumEntity *model=[_searchArray objectAtIndex:indexPath.row];
        
        TalkDetailController *vc = [[TalkDetailController alloc] init];
        vc.model = model;
        [self openPushVC:vc];
    }else{
        User *entity=[_searchArray objectAtIndex:indexPath.row];
        
        UserInfoController *vc = [[UserInfoController alloc] init];
        vc.user_id = entity.user_id;
        [self openPushVC:vc];
    }
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger count = _searchArray.count;
    if((indexPath.row+1) < count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
